package com.chcit.mobile.mvp.receive.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.mobile.app.base.ScanOrZxingFragment;
import com.chcit.mobile.app.base.ScanToolFragment;
import com.google.android.material.textfield.TextInputEditText;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.BuildConfig;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerReceiveComponent;
import com.chcit.mobile.di.module.ReceiveModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.receive.contract.ReceiveContract;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.ReceiveBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.receive.presenter.ReceivePresenter;
import com.chcit.mobile.mvp.common.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.receive.adpter.ReceiveAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.edittext.ValidatorEditText;
import com.xuexiang.xui.widget.toast.XToast;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 入库搜索页面
 */
@Deprecated
public class OldReceiveFragment extends ScanToolFragment<ReceivePresenter> implements ReceiveContract.View {
    @BindView(R.id.et_receive_list_package_document_no)
    ValidatorEditText etReceiveListPackageDocumentNo;
    @BindView(R.id.img_receive_list_scan)
    AppCompatImageView imgScan;
    @BindView(R.id.bt_receive_list_query)
    Button btQuery;
    @BindView(R.id.ckb_select_all)
    CheckBox selectAll;
    @BindView(R.id.bt_batch_confirm)
    Button btBatchConfirm;
    @BindView(R.id.linear_layout_show)
    LinearLayoutCompat mLinearLayout;
    @BindView(R.id.pr_receive_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_show_select)
    TextView tvShowSelect;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    ReceiveAdapter mAdapter;
    protected MenuTypeEnum type; //入库类型  采购-PO
    private ArrayList<BpartnerBean> bpartners;
    private TextInputEditText tietProductName;
    private BpartnerBean bpartnerBean;
    private String headers[] = {"选择供应商", "输入商品", "一周内","入库类型"};
    private int dateTime = 1;//选择的日期 0没选择  1-1月内  2-2月内  3-3月内
    private ReceiveBean receiveBean;
    private static int REQUEST_CODE = -2;
    private String asnType;
    private String page;
    private Statu user;//第二负责人
    public static OldReceiveFragment newInstance() {
        OldReceiveFragment fragment = new OldReceiveFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerReceiveComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .receiveModule(new ReceiveModule(this))
                .build()
                .inject(this);
    }



    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
        imgScan.setOnClickListener(v->{
            initZxing();
        });
        mAdapter.setType(type);
        etReceiveListPackageDocumentNo.setHint("请扫码包装号/箱号/单号");
        initDropDownMenu();

    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(getContext());
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
         XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(type.equals(MenuTypeEnum.PURCHASE_CHECK)){
//            String[] invoiceList = barcodeData.split(",");
            int startIndex=0 , endIndex=0, count = 0;
            for(int i = 0; i < barcodeData.length(); i++){
                char c = barcodeData.charAt(i);
                if(c == ','){
                    ++count;
                    if(count == 3){
                        startIndex = i+1;
                    }else if(count == 4){
                        endIndex =i;
                    }
                }

            }
            if(count >= 8){
                etReceiveListPackageDocumentNo.setText(barcodeData.substring(startIndex,endIndex));
                btQuery.performClick();
                return;
            }
        }
        etReceiveListPackageDocumentNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mAdapter.checkAll();
                } else {
                    mAdapter.cancelAll();
                }
            }
        });

    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(getContext());
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean(1,"不限"));
        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(getContext(), bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });
        //商品选择
        final View constellationView = getLayoutInflater().inflate(R.layout.custom_layout, null);
        tietProductName = constellationView.findViewById(R.id.constellation);
        TextView ok = constellationView.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tietProductName.getText().toString();
                mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
            }
        });

        //日期选择
        final ListView dateView = new ListView(getContext());
        List<String> dates = Arrays.asList("不限", "一周内", "二周内", "三周内");
        final GirdDropDownAdapter<String> dateAdapter = new GirdDropDownAdapter<String>(getContext(), dates);
        dateAdapter.setCheckItem(1);
        dateView.setDividerHeight(0);
        dateView.setAdapter(dateAdapter);
        dateView.setOnItemClickListener((parent, view, position, id) -> {
            dateAdapter.setCheckItem(position);
            dateTime = position;
            mDropDownMenu.setTabText(position == 0 ? "选择日期" : dates.get(position));
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);
        //入库类型选择
        asnType = type.getType();
        page = "receive";
//        if(BuildConfig.TYPE.equals("GLYY")){
//            page = "check";
//        }else{
//            page = "receive";
//        }
        switch (type){
            case PURCHASE_CHECK:
                page = "check";
                headers = new String[]{"选择供应商", "输入商品", "一周内"};
                etReceiveListPackageDocumentNo.setHint("请扫码包装号/箱号/单号/发票号");
                break;
            case PURCHASE_RECEIVE:
                page = "receive";
                headers = new String[]{"选择供应商", "输入商品", "一周内"};
                break;
            case YN_RECEIVE:
                page = "receive";
                final ListView receiveTypeView = new ListView(getContext());
                List<Statu> receiveTypes = new ArrayList<>();
                receiveTypes.add(new Statu( "WO,WR,MO","不限"));
                receiveTypes.add(new Statu("WO","请领"));
                receiveTypes.add(new Statu( "WR","退库"));
                receiveTypes.add(new Statu("MO","库间调拨"));
                final GirdDropDownAdapter<Statu> receiveTypeAdapter = new GirdDropDownAdapter<Statu>(getContext(), receiveTypes);
                receiveTypeView.setDividerHeight(0);
                receiveTypeView.setAdapter(receiveTypeAdapter);
                receiveTypeView.setOnItemClickListener((parent, view, position, id) -> {
                    receiveTypeAdapter.setCheckItem(position);
                    asnType = receiveTypes.get(position).getId();
                    mDropDownMenu.setTabText(position == 0 ? headers[3] : receiveTypes.get(position).getName());
                    mDropDownMenu.closeMenu();
                });
                popupViews.add(receiveTypeView);
                break;
            case YN_CHECK:
                page = "check";
                final ListView receiveTypeView2 = new ListView(getContext());
                List<Statu> receiveTypes2 = new ArrayList<>();
                receiveTypes2.add(new Statu( "WO,WR,MO","不限"));
                receiveTypes2.add(new Statu("WO","请领"));
                receiveTypes2.add(new Statu( "WR","退库"));
                receiveTypes2.add(new Statu("MO","库间调拨"));
                final GirdDropDownAdapter<Statu> receiveTypeAdapter2 = new GirdDropDownAdapter<Statu>(getContext(), receiveTypes2);
                receiveTypeView2.setDividerHeight(0);
                receiveTypeView2.setAdapter(receiveTypeAdapter2);
                receiveTypeView2.setOnItemClickListener((parent, view, position, id) -> {
                    receiveTypeAdapter2.setCheckItem(position);
                    asnType = receiveTypes2.get(position).getId();
                    mDropDownMenu.setTabText(position == 0 ? headers[3] : receiveTypes2.get(position).getName());
                    mDropDownMenu.closeMenu();
                });
                popupViews.add(receiveTypeView2);
                break;
            case REJECT:
                mCommonToolbar.setTitleText("拒收入库");
                headers = new String[]{"选择供应商", "输入商品", "一周内"};
                page = "rejectReceive";
//                if(Build.TYPE.equals("GLYY")){
//                    page = "rejectReceive";
//                }
                break;
        }


        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("筛选条件");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.BOTTOM);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 14);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView,new Float[]{6f,6f,4f,4f});

        mPresenter.getBpartners(String.valueOf(HttpClientHelper.getSelectWareHouse().getId()),bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });

    }

    @OnClick({R.id.bt_receive_list_query, R.id.bt_batch_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_receive_list_query:
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                String asnNo = etReceiveListPackageDocumentNo.getText().toString();
                String productName = tietProductName.getText().toString();
                JSONObject data = new JSONObject();
                data.put("page", page);//
                data.put("asnType", asnType);
                if (!asnNo.isEmpty()) {
                    data.put("asnNo", asnNo);
                }
                if (dateTime > 0) {
                    String dataArrivedFrom = TimeDialogUtil.getBeforeDay(dateTime);
                    data.put("dataArrivedFrom", dataArrivedFrom);
                }
                if (!productName.isEmpty()) {
                    data.put("productName", productName);
                }
                if (bpartnerBean != null && bpartnerBean.getId()!= 1) {
                    data.put("bpartnerId", bpartnerBean.getId());
                }

                mPresenter.getData(HttpMethodContains.PURCHASE_RECEVIE_QUERY_DETAIL,data);
                break;
          /*  case R.id.bt_receive_date_to:
                Calendar calendarTo = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_to,calendarTo);
                break;
            case R.id.bt_receive_date_from:
                Calendar calendarFrom = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_from,calendarFrom);
                break;*/
            case R.id.bt_batch_confirm:
                doBatchConfirm();
                break;
        }
    }



    private int itemPosition = -1;

    private void initRecyclerView() {
        mAdapter.setTitleBarView(tvShowSelect);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                itemPosition = position;
                if(position>=0&& adapter.getData().size()>position){
                    toDeal(position);
                }
//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
            }
        });
        mRecyclerView.setAdapter(mAdapter);

    }

    private void toDeal(int position) {

        receiveBean = mAdapter.getData().get(position);
        if("Y".equals(receiveBean.getIsStoragePackage())){
            startForResult(ReceiveScanPackageFragment.newInstance(receiveBean,type), REQUEST_CODE);
        }else{
            if("BZ".equals(BuildConfig.TYPE)){
                startForResult(ReceiveDetailFragment.newInstance(receiveBean,type), REQUEST_CODE);
            }else{
                startForResult(ReceiveOldDetailFragment.newInstance(receiveBean,type), REQUEST_CODE);
            }


        }
    }

    /**
     * 当有数据返回时，回调
     *
     * @param requestCode 返回状态码
     * @param resultCode  是否成功状态码
     * @param data        返回数据
     */
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE ) {
            if(resultCode == RESULT_OK){
                if(data != null){
                    btQuery.performClick();
                    //onBarcodeEventSuccess(receiveBean.getDeliveryNo());
                }else if(mAdapter.getData().size() >0){
                    mAdapter.remove(itemPosition);
                    if(mAdapter.getData().size() >0){
                        itemPosition ++;
                        if(mAdapter.getData().size()>itemPosition){
                            toDeal(itemPosition);
                        }else{
                            btQuery.performClick();
                        }
                    }
                }
            }else if(resultCode == -2){
                itemPosition ++;
                if(mAdapter.getData().size()>itemPosition){
                    toDeal(itemPosition);
                }
            }else if(requestCode == -3){
                mAdapter.remove(itemPosition);
            }

        }

    }

    @Override
    public <E> void updateContentList(List<E> receiveBeans) {

            mAdapter.addData((List<ReceiveBean>) receiveBeans);
            mAdapter.notifyDataSetChanged();
            mLinearLayout.setVisibility(View.VISIBLE);
            if(mAdapter.getData().size() == 1){
                receiveBean = mAdapter.getData().get(0);
                itemPosition = 0;
                toDeal(0);
            }
    }

    @Override
    public <T extends View> T getViewByTag(int i) {
        switch (i) {
            case 1:
                return (T) btQuery;
            case 2:
                break;

        }
        return null;
    }

    private void doBatchConfirm() {
        final ArrayList<ReceiveBean> datas = mAdapter.getSelectedItem();
        if (datas.size() == 0) {
            DialogUtil.showErrorDialog(getContext(),  "请选择至少一项");
            return;
        }
        SparseArray<JSONArray> asnIds = new SparseArray<JSONArray>();
        asnIds.put(datas.get(0).getAsnId(),new JSONArray());
        boolean isSecondChange = false;
        boolean isNeerGuarantee = false;
        StringBuilder content = new StringBuilder();
        for (ReceiveBean prb : datas) {
            if("Y".equals(prb.getIsStoragePackage())){
                continue;
            }
            if("Y".equals(prb.getIsControlledProduct())&&!isSecondChange){
                isSecondChange = true;
            }
            if("Y".equals(prb.getIsNeerGuarantee())&&!isNeerGuarantee){
                isNeerGuarantee = true;
                content.append(prb.getError()+"/n");
            }
            int i = asnIds.indexOfKey(prb.getAsnId());
            JSONArray asnLineIds = null;
            if(i>-1){
                asnLineIds = asnIds.get(prb.getAsnId());
            }
            if(asnLineIds!=null){
                asnLineIds.add(prb.getAsnLineId());
            }else{
                asnLineIds = new JSONArray();
                asnLineIds.add(prb.getAsnLineId());
                asnIds.put(prb.getAsnId(),asnLineIds);
            }

        }
         JSONArray params = new JSONArray();
        if(asnIds.size()==0){
            DialogUtil.showErrorDialog(getContext(), "包装管理不允许批量收货！");
            return;
        }
        for(int i= 0;i<asnIds.size();i++){
            JSONObject asnId = new JSONObject();
            int key =asnIds.keyAt(i);
            asnId.put("asnId",key);
            asnId.put("asnLineId", asnIds.get(key));
            params.add(asnId);

        }
        JSONObject data = new JSONObject();
        data.put("recieve", params);//
        content.append("确定要批量提交").append(datas.size()).append("个商品吗?");
        if(isSecondChange){
            if(user == null){
                HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                    if(HttpClientHelper.getUser()!= null){
                        this.user = user;
                        data.put("workerId2",user.getId());
                        showConfrimDialog(content,datas, data);
                    }
                });
                return;
            }else{
                data.put("checkUser2Id",user.getId());
            }

        }
        showConfrimDialog(content,datas, data);


    }

    private void showConfrimDialog(StringBuilder content,ArrayList<ReceiveBean> datas, JSONObject data) {
        new MaterialDialog.Builder(Objects.requireNonNull(getContext()))
                .title("批量收货")
                .content(content)
                .items(datas)
                // .iconRes(R.drawable.icon)
                .positiveText("确认")
                .negativeText("取消")
                //点击事件添加 方式1
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        //{recieve:[{asnId:12212,asnLineId:[1111,2323,343434]},{asnId:12212,asnLineId:[1111,2323,343434]}]}

                        mPresenter.doBatchConfirm(data,()->{
                            List<Integer> list = this.mAdapter.getSelectedItemPosition();
                            int k = list.size();
                           for(int i= k-1; i>=0;i-- ){
                                 this.mAdapter.remove(list.get(i));
                                  //mAdapter.remove(i);
                           }
                           mAdapter.clearSelectItem();
                           mAdapter.getTitleBarView().setText("");
                           showMessage("处理成功！");

                        });
                        dialog.dismiss();
                        // Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                    } else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                })
                .show();
    }

    public Statu getUser() {
        return user;
    }

    public void setUser(Statu user) {
        this.user = user;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_receive;
    }
}
